/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
/*
 * @description: 路由相关配置
 * @fileName: index.ts
 * @author: zoujunjie
 * @date: 2022-07-05
 */
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import localTokenStrategy from "@/common/util/auth";
import { getMenuPermissionsFromCache } from "@/services/user-permission";
import { logout } from "@/services/user";
import { getOrganizationUserMenuItemByPath } from "@/common/menu";

let getAdminRoutes = (): Array<RouteRecordRaw> => {
  let sytemManagementRoutes: Array<RouteRecordRaw> = [
    {
      path: "organization",
      component: () =>
        import("@/views/Admin/SystemManagement/Organization/organization.vue"),
    },
  ];
  sytemManagementRoutes.forEach(
    (item) => (item.path = `system-management/${item.path}`)
  );
  return [...sytemManagementRoutes];
};

let getTaskScheduleRoutes = (): Array<RouteRecordRaw> => {
  let routes: Array<RouteRecordRaw> = [
    {
      path: "dashboard",
      component: () => import("@/views/TaskSchedule/Dashboard/Dashboard.vue"),
    },
    {
      path: "resource",
      component: () =>
        import("@/views/TaskSchedule/TaskResources/task-resouces.vue"),
    },
    {
      path: "arrangement",
      component: () =>
        import("@/views/TaskSchedule/TaskArrangement/task-arrangement.vue"),
    },
    {
      path: "host-config",
      component: () =>
        import("@/views/TaskSchedule/HostConfig/host-config.vue"),
    },
    {
      path: "service-node",
      component: () =>
        import("@/views/TaskSchedule/ServiceNode/service-node.vue"),
    },
    {
      path: "allocation-resources",
      component: () =>
        import(
          "@/views/TaskSchedule/AllocationResources/allocation-resources.vue"
        ),
    },
    {
      path: "task-instance",
      component: () =>
        import("@/views/TaskSchedule/TaskInstance/task-instance.vue"),
    },
    {
      path: "slot-manage",
      component: () => import("@/views/TaskSchedule/SlotManage/SlotManage.vue"),
    },
  ];
  routes.forEach((item) => (item.path = `task-schedule/${item.path}`));
  return routes;
};

let getSystemManagementRoutes = (): Array<RouteRecordRaw> => {
  let routes: Array<RouteRecordRaw> = [
    {
      path: "/log",
      name: "log",
      component: () => import("@/views/SystemManage/Log/log.vue"),
    },
    {
      path: "/user-manage",
      name: "userManage",
      component: () =>
        import("@/views/SystemManage/UserManage/user-manage.vue"),
    },
    {
      path: "/role",
      name: "role",
      component: () => import("@/views/SystemManage/Role/role.vue"),
    },
    {
      path: "/config",
      component: () => import("@/views/SystemManage/config/config.vue"),
    },
    {
      path: "/message",
      component: () => import("@/views/SystemManage/Message/Message.vue"),
    },
  ];
  routes.forEach((item) => (item.path = `system-management/${item.path}`));
  return routes;
};

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("@/layouts/Default/Default.vue"),
    redirect: "/task-schedule/dashboard",
    children: [
      {
        path: "error/403",
        component: () => import("@/views/Error/403.vue"),
      },
      {
        path: "message",
        name: "我的消息",
        component: () => import("@/views/Message/Message.vue"),
      },
      ...getTaskScheduleRoutes(),
      ...getSystemManagementRoutes(),
    ],
  },
  {
    path: "/login",
    component: () => import("@/views/Login.vue"),
  },
  {
    path: "/admin",
    component: () => import("@/layouts/Default/Default.vue"),
    redirect: "/admin/system-management/organization",
    children: [...getAdminRoutes()],
  },
  {
    path: "/admin/login",
    component: () => import("@/views/Admin/Login/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import("@/views/Error/404.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

const allowAnonymityPaths: string[] = ["/login", "/admin/login"];

router.beforeEach((to, from, next) => {
  if (allowAnonymityPaths.indexOf(to.path) > -1) {
    next();
    return;
  }
  if (
    localTokenStrategy.validToken((token) => {
      console.log("validateTokenCallback", token);
    })
  ) {
    let user = localTokenStrategy.getUserInfo();
    if (to.path.startsWith("/admin")) {
      //管理员用户页面
      if (user.isAdmin) {
        next();
        return;
      }
    } else {
      //组织用户页面
      if (!user.isAdmin) {
        let keys = getMenuPermissionsFromCache();
        let menuItem = getOrganizationUserMenuItemByPath(to.path);
        if (menuItem && keys.findIndex((x) => x == menuItem?.key) < 0) {
          next({ path: "/error/403" });
        } else {
          next();
        }
        return;
      }
    }
  }
  logout();
  next({
    path: to.path.startsWith("/admin") ? "/admin/login" : "/login",
    query: {
      returnUrl: to.fullPath,
    },
  });
});

export default router;
